
package com.bear.cmcc.NetTestHTTP.util;

import com.bear.cmcc.NetTestHTTP.component.CountryBean;
import com.bear.cmcc.NetTestHTTP.component.ProvinceBean;
import com.bear.cmcc.NetTestHTTP.component.ServersConfigBean;
import com.bear.cmcc.NetTestHTTP.component.VillageBean;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.util.Log;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Vector;

public class JsonUtil {

    private static final String TAG = "JsonUtil";

    public static final String JSON_Device = "Device";

    public static final String JSON_Province = "Province";

    public static final String JSON_AverageSpeed = "AverageSpeed";

    public static final String JSON_Provinces = "Provinces";

    public static final String JSON_name = "name";

    public static final String JSON_Rank = "Rank";

    public static final String JSON_citys = "citys";

    public static final String JSON_signalStrength = "signalStrength";

    public static final String JSON_electricalLevel = "electricalLevel";

    public static final String JSON_droppingRate = "droppingRate";

    public static final String ALL_NAME = "全国";

    /**
     * 最好的
     */
    public static final String JSON_TOP = "top";

    /**
     * 最差的。
     */
    public static final String JSON_BOTTOM = "bottom";

    /**
     * 福建小区TOP10
     */
    public static final String JSON_TOP_FJ_VALLIAGE = "TOP10";

    /**
     * 福建小区BOTTOM10
     */
    public static final String JSON_BOTTOM_FJ_VALLIAGE = "BOTTOM10";

    public static final String JSON_FJ_LAC = "LAC";

    public static final String JSON_FJ_CI = "CI";

    public static final String JSON_FJ_NAME = "NAME";

    /**
     * 解析福建top10数据。
     * 
     * @param context
     * @param file 要解析的文件。
     * @param isTop 是最好的城市，还是最差的。
     * @return ArrayList<String[]> 一定不为null
     */
    public static ArrayList<VillageBean> parseFjTop10Data(Context context, File file, boolean isTop) {
        ArrayList<VillageBean> data = new ArrayList<VillageBean>();
        if (file != null && context != null) {
            String key = (isTop ? JSON_TOP_FJ_VALLIAGE : JSON_BOTTOM_FJ_VALLIAGE);
            JSONObject scoreData = parseJson(file);
            int max = 10;// 城市排名最大值
            int min = 1;// 城市排名最小值

            if (scoreData != null) {
                // 解析福建top10城市信息。
                try {
                    JSONObject top10CityData = scoreData.getJSONObject(key);
                    JSONObject jsonObjTwo = null;
                    JSONObject jsonObjThree = null;
                    if (top10CityData != null) {
                        String[] codes = MyCommonUtil.getFjCityCodeByCityCode();
                        VillageBean village = null;
                        for (String city_code : codes) {
                            jsonObjTwo = top10CityData.getJSONObject(city_code);
                            if (jsonObjTwo == null) {
                                continue;
                            }
                            for (int i = min; i <= max; i++) {
                                village = new VillageBean();
                                village.setCity_code(city_code);// 设置城市代码
//                                village.setRand(i);// 设置小区排名
                                jsonObjThree = jsonObjTwo.getJSONObject(i + "");
                                village.setLac(jsonObjThree.getInt(JSON_FJ_LAC));
                                village.setCi(jsonObjThree.getInt(JSON_FJ_CI));
                                village.setVillage_name(jsonObjThree.getString(JSON_FJ_NAME));
                                village.setAverageSpeed(jsonObjThree.getDouble(JSON_AverageSpeed));
                                data.add(village);
                            }
                        }

                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
        return data;
    }

    /**
     * 按城市代码解析福建top10数据。
     * 
     * @param context
     * @param file 要解析的文件。
     * @param isTop 是最好的城市，还是最差的。
     * @param cityCode
     * @return ArrayList<String[]> 一定不为null
     */
    public static ArrayList<VillageBean> parseFjTop10Data(Context context, File file,
            boolean isTop, String cityCode) {
        ArrayList<VillageBean> data = new ArrayList<VillageBean>();
        if (file != null && context != null && cityCode != null) {
            String key = (isTop ? JSON_TOP_FJ_VALLIAGE : JSON_BOTTOM_FJ_VALLIAGE);
            JSONObject scoreData = parseJson(file);
            int max = 10;// 城市排名最大值
            int min = 1;// 城市排名最小值

            if (scoreData != null) {
                // 解析福建top10城市信息。
                try {
                    JSONObject top10CityData = scoreData.getJSONObject(key);
                    JSONObject jsonObjTwo = null;
                    JSONObject jsonObjThree = null;
                    if (top10CityData != null) {
                        VillageBean village = null;
                        jsonObjTwo = top10CityData.getJSONObject(cityCode);
                        if (jsonObjTwo != null) {

                            for (int i = min; i <= max; i++) {
                                village = new VillageBean();
                                village.setCity_code(cityCode);// 设置城市代码
//                                village.setRand(i);// 设置小区排名
                                jsonObjThree = jsonObjTwo.getJSONObject(i + "");
                                village.setLac(jsonObjThree.getInt(JSON_FJ_LAC));
                                village.setCi(jsonObjThree.getInt(JSON_FJ_CI));
                                village.setVillage_name(jsonObjThree.getString(JSON_FJ_NAME));
                                village.setAverageSpeed(jsonObjThree.getDouble(JSON_AverageSpeed));
                                data.add(village);
                            }
                        }

                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
        return data;
    }

    /**
     * 解析top10数据。
     * 
     * @param context
     * @param file 要解析的文件。
     * @param isTop 是最好的城市，还是最差的。
     * @return ArrayList<String[]> 一定不为null，String[3]{城市名称,速度,排名} {福州,24.5,1}
     */
    public static ArrayList<String[]> parseTop10Data(Context context, File file, boolean isTop) {
        ArrayList<String[]> data = new ArrayList<String[]>();
        if (file != null && context != null) {
            String key = (isTop ? JSON_TOP : JSON_BOTTOM);

            JSONObject scoreData = parseJson(file);

            if (scoreData != null) {
                // 解析top10城市信息。
                try {
                    JSONArray top10CityData = scoreData.getJSONArray(key);
                    JSONObject jsonObj = null;
                    if (top10CityData != null) {
                        for (int i = 0; i < top10CityData.length(); i++) {
                            jsonObj = ((JSONObject) top10CityData.opt(i));

                            if (jsonObj != null) {
                                data.add(new String[] {
                                        jsonObj.getString(JSON_name),
                                        jsonObj.getString(JSON_AverageSpeed),
                                        jsonObj.getString(JSON_Rank)
                                });
                            }
                        }

                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }

        return data;
    }

    /**
     * 解析Score_TD文件数据。
     * 
     * @param context
     * @param file
     * @return
     */
    public static boolean parseScore_TDJson(Context context, File file, CountryBean bean) {
        if (file == null || context == null || bean == null) {
            return false;
        }
        String deviceId = MyCommonUtil.getDeviceId(context);
        String deviceMd5 = MyCommonUtil.getDeviceByMD5(deviceId);
        try {
            JSONObject scoreTD = parseJson(file);
            if (scoreTD != null) {
                JSONObject temp = scoreTD.getJSONObject(JSON_Province);
                double totalAverageSpeedTD = temp.getJSONObject(ALL_NAME).getDouble(
                        JSON_AverageSpeed);
                bean.setAverageSpeed_TD(totalAverageSpeedTD);

                // 获取设备数量。
                JSONObject deviceAll = scoreTD.getJSONObject(JSON_Device);
                bean.setDeviceTDAll(deviceAll);
                int deviceTotalTD = deviceAll.length();
                bean.setSize_TD(deviceTotalTD);
                if (deviceMd5 != null) {
                    bean.setSelfDeviceIdMd5(deviceMd5);
                    // 当前设备有可能不是2G
                    try {
                        JSONObject deviceInfo = deviceAll.getJSONObject(deviceMd5);
                        if (deviceInfo != null) {
                            bean.setSelfAverageSpeed(deviceInfo.getDouble(JSON_AverageSpeed));
                            bean.setSelfRand(deviceInfo.getInt(JSON_Rank));
                        }
                    } catch (Exception e) {
                        Log.d(TAG, "deviceInfo is not td");
                    }
                }

                // 解析城市信息。
                JSONArray province2Garray = scoreTD.getJSONArray(JSON_Provinces);

                if (province2Garray != null) {
                    JSONObject jsonObj = null;
                    ProvinceBean pro = null;
                    for (int i = 0; i < province2Garray.length(); i++) {
                        jsonObj = ((JSONObject) province2Garray.opt(i));
                        pro = new ProvinceBean();
                        pro.setProvince_name(jsonObj.getString(JSON_name));
                        pro.setTd_downSpeed(jsonObj.getString(JSON_AverageSpeed));
                        pro.setTd_Rand(jsonObj.getInt(JSON_Rank));
                        pro.setCitys_td(jsonObj.getJSONArray(JSON_citys));

                        bean.addPri_TD(pro);
                    }
                }

            }
        } catch (JSONException e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }

    /**
     * 解析Score_2G文件数据。
     * 
     * @param context
     * @param file
     * @return
     */
    public static boolean parseScore_2GJson(Context context, File file, CountryBean bean) {
        if (file == null || context == null || bean == null) {
            return false;
        }
        String deviceId = MyCommonUtil.getDeviceId(context);
        String deviceMd5 = MyCommonUtil.getDeviceByMD5(deviceId);
        try {
            JSONObject score2G = parseJson(file);
            if (score2G != null) {
                JSONObject temp = score2G.getJSONObject(JSON_Province);
                double totalAverageSpeed2G = temp.getJSONObject(ALL_NAME).getDouble(
                        JSON_AverageSpeed);
                bean.setAverageSpeed_2G(totalAverageSpeed2G);

                // 获取设备数量。
                JSONObject deviceAll = score2G.getJSONObject(JSON_Device);
                bean.setDevice2GAll(deviceAll);
                int deviceTotal2G = deviceAll.length();
                bean.setSize_2G(deviceTotal2G);

                if (deviceMd5 != null) {
                    bean.setSelfDeviceIdMd5(deviceMd5);
                    // 当前设备有可能不是TD设备。
                    try {
                        JSONObject deviceInfo = deviceAll.getJSONObject(deviceMd5);
                        if (deviceInfo != null) {
                            bean.setSelfAverageSpeed(deviceInfo.getDouble(JSON_AverageSpeed));
                            bean.setSelfRand(deviceInfo.getInt(JSON_Rank));
                        }
                    } catch (Exception e) {
                        Log.d(TAG, "deviceInfo is not 2G");
                    }
                }

                // 解析城市信息。
                JSONArray province2Garray = score2G.getJSONArray(JSON_Provinces);

                if (province2Garray != null) {
                    JSONObject jsonObj = null;
                    ProvinceBean pro = null;
                    for (int i = 0; i < province2Garray.length(); i++) {
                        jsonObj = ((JSONObject) province2Garray.opt(i));
                        pro = new ProvinceBean();
                        pro.setProvince_name(jsonObj.getString(JSON_name));
                        pro.setGprs_downSpeed(jsonObj.getString(JSON_AverageSpeed));
                        pro.setTwoG_Rand(jsonObj.getInt(JSON_Rank));
                        pro.setCitys_2g(jsonObj.getJSONArray(JSON_citys));

                        bean.addPri_2G(pro);
                    }
                }

            }
        } catch (JSONException e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }

    /**
     * 解析服务端的配置(JSON)
     * 
     * @param context
     * @return
     */
    public static List<ServersConfigBean> getServersConfigs(Context context, File file) {
        JSONObject serversObj = parseJson(file);
        if (serversObj == null) {
            return null;
        }
        try {
            List<ServersConfigBean> list = new ArrayList<ServersConfigBean>();
            JSONArray jsonArray = new JSONArray(serversObj.getString(ServersConfigBean.JSON_ROOT));
            for (int i = 0; i < jsonArray.length(); i++) {
                ServersConfigBean b = new ServersConfigBean();
                JSONObject obj = jsonArray.getJSONObject(i);
                b.setServerName(obj.getString(ServersConfigBean.JSON_ServerName));
                b.setServerAddress(obj.getString(ServersConfigBean.JSON_ServerAddress));
                b.setServerPort(obj.getString(ServersConfigBean.JSON_ServerPort));
                b.setDownloadName(obj.getString(ServersConfigBean.JSON_downloadName));
                b.setDownloadPwd(obj.getString(ServersConfigBean.JSON_downloadPwd));
                b.setDownloaddictory(obj.getString(ServersConfigBean.JSON_downloaddictory));
                list.add(b);
            }
            return list;
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }
    
    public static int getAllDeviceNum(CountryBean bean)
    {
    	try
    	{
    	String device2GAll = bean.getDevice2GAll().toString();
    	String deviceTDAll = bean.getDeviceTDAll().toString();
    	ArrayList<String> device2GList = new ArrayList<String>();
    	ArrayList<String> deviceTDList = new ArrayList<String>();
    	String fg = "\"},\"";
    	String[] temp2G  = splitString(fg, device2GAll);
    	for(int i=0;i<temp2G.length;i++)
    	{
    		device2GList.add(temp2G[i].substring(0, temp2G[i].indexOf("\":")));
    	}
    	String[] tempTD  = splitString(fg, deviceTDAll);
    	for(int i=0;i<tempTD.length;i++)
    	{
    		deviceTDList.add(tempTD[i].substring(0, tempTD[i].indexOf("\":")));
    	}
    	ArrayList<String> allDevice = compare(device2GList, deviceTDList);
    	if(allDevice != null)
    		return allDevice.size();
    	else
    		return 0;
    	}catch(Exception ex)
    	{
    		Log.d(TAG, "getAllDeviceNum Exception =" + ex.getMessage());
    		return 0;
    	}
    	
    }
    
    /**
     * 对比两个数组，取出不重的部分
     * @param device2gList
     * @param deviceTDList
     * @return
     */
    private static ArrayList<String> compare(ArrayList<String> device2gList, ArrayList<String> deviceTDList) {
		ArrayList<String> list2 = new ArrayList<String>();
		for (String t : deviceTDList) {
			if (!device2gList.contains(t)) {
				list2.add(t);
			}
		}
		return list2;
	}

    /**
     * 把json文件读取成JSONObject对象。
     * 
     * @param file
     * @return JSONObject对象。
     */
    private static JSONObject parseJson(File file) {
        JSONObject result = null;
        if (file == null || !file.exists()) {
            return result;
        }
        try {
            FileReader fr = null;
            BufferedReader buff = null;
            StringBuffer contents = new StringBuffer();
            String text = null;

            fr = new FileReader(file);
            buff = new BufferedReader(fr);
            text = null;
            while ((text = buff.readLine()) != null) {
                contents.append(text);
            }

            result = new JSONObject(contents.toString());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return result;

    }
    
    /**
     * 自定义分隔字符串方法
     * @param fgf
     * @param content
     * @return
     */
    public static String[] splitString(String fgf, String content) {
		String[] result = null;
		if (content.indexOf(fgf) == -1) {
			result = new String[1];
			result[0] = content;

		} else {
			Vector vector = new Vector();
			int nowposition = 0;
			int nextpos;
			String temp;
			nextpos = content.indexOf(fgf, nowposition);
			temp = read(fgf, content, nowposition, nextpos);
			while (temp != "") {
				vector.add(temp);
				nowposition = nextpos + fgf.length();
				nextpos = content.indexOf(fgf, nowposition);
				if (nextpos < 0 && nowposition < content.length())// 如果现在为止不是最后，当时又找不到下一个分隔符的位置，说明当前这个是最后一个，直接加入，退出
				{
					temp = read(fgf, content, nowposition, content.length());
					vector.add(temp);
					break;
				}
				temp = read(fgf, content, nowposition, nextpos);
			}
			if (content.substring(content.length() - fgf.length(),
					content.length()).equals(fgf))// 如果最后一个是fgf，添加最后一个数组纬度，内容为“”
				result = new String[vector.size() + 1];
			else
				result = new String[vector.size()];
			for (int i = 0; i < vector.size(); i++) {
				result[i] = vector.elementAt(i).toString();
			}
			if (content.substring(content.length() - fgf.length(),
					content.length()).equals(fgf))
				result[result.length - 1] = "";
		}
		return result;
	}
    
    private static String read(String FGF, String content, int nowposition,
			int nextpos) {
		if (nextpos < 0) {
			return "";
		} else {
			String result = content.substring(nowposition, nextpos);
			return result;
		}
	}

}
